package site.zhanjingbo.HelloMyBatis;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import site.zhanjingbo.HelloMyBatis.dao.UserDao;
import site.zhanjingbo.HelloMyBatis.model.User;

public class MybaitsBase {

	public static void main(String[] args) {
		// addDemo();
		// updateDemo();
		// deleteDemo();
		// queryDemo();
	}

	public static void queryDemo() {
		String resource = "Mybatis.xml";
		InputStream in = MybaitsBase.class.getClassLoader().getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);

		SqlSession session = sqlSessionFactory.openSession();
		try {
			UserDao userDao = session.getMapper(UserDao.class);
			User user = userDao.getUser(12);
			System.out.println(user);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public static void updateDemo() {
		String resource = "Mybatis.xml";
		InputStream in = MybaitsBase.class.getClassLoader().getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);

		SqlSession session = sqlSessionFactory.openSession(true);
		try {
			UserDao userDao = session.getMapper(UserDao.class);
			User user = new User(12, "XX", "corp");
			userDao.updateUser(user);
			System.out.println(user);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public static void deleteDemo() {
		String resource = "Mybatis.xml";
		InputStream in = MybaitsBase.class.getClassLoader().getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);

		SqlSession session = sqlSessionFactory.openSession(true);
		try {
			UserDao userDao = session.getMapper(UserDao.class);
			userDao.deleteUser(12);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public static void addDemo() {
		User user = new User(0, "addUser", "addUser");
		String resource = "Mybatis.xml";
		InputStream in = MybaitsBase.class.getClassLoader().getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);

		SqlSession session = sqlSessionFactory.openSession(true);
		try {
			UserDao userDao = session.getMapper(UserDao.class);
			userDao.addUser(user);
			System.out.println(user);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}
